# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：   base_email
   Author :      wuqianyong
   date：        2019/11/21
-------------------------------------------------
   Change Activity:
                   2017/4/1:
-------------------------------------------------
Description :
 

"""
__author__ = 'wuqianyong'
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.application import MIMEApplication
from email.utils import formataddr

from email.utils import parseaddr
import smtplib
import os


 
def __format_addr__(addr):
    # 解析邮件地址，以保证邮有别名可以显示
    alias_name, a = parseaddr(addr)
    # 防止中文问题，进行转码处理，并格式化为str返回
    return formataddr((Header(alias_name,charset="utf-8").encode(),a))


def send_email(title, content, to_addr=None,doc=None):
    """发送邮件--qq 企业邮箱"""
    # 用户信息
    from_addr = 'wuqianyong@zhongan.com'
    if not to_addr:
        to_addr = from_addr
    password = 'jEeKhSdPv3HXCuW8'  # # 腾讯QQ邮箱或腾讯企业邮箱必须使用授权码进行第三方登陆
    # to_addr = '1060591592@qq.com'
    smtp_server = 'smtp.exmail.qq.com'  # 腾讯服务器地址

    # 内容初始化，定义内容格式（普通文本，html）
    # msg = MIMEText(msg, 'plain', 'utf-8')
    msg = MIMEMultipart()
    msg.attach(MIMEText(content, 'plain', 'utf-8'))

    # 发件人收件人信息格式化 ，可防空
    # 固定用法不必纠结，我使用lambda表达式进行简单封装方便调用
    lam_format_addr = lambda name, addr: formataddr((Header(name, 'utf-8').encode(), addr))
    # 传入昵称和邮件地址
    msg['From'] = lam_format_addr("众安吴钱勇", from_addr)  # 腾讯邮箱可略
    # msg['To'] = lam_format_addr('Yong', to_addr)  # 腾讯邮箱可略
    # msg['To'] = [__format_addr__(a) for a in to_addr]  # 腾讯邮箱可略
    msg['To'] =  lam_format_addr('王浩庭', to_addr)  # 腾讯邮箱可略

    # 邮件标题
    msg['Subject'] = Header(title, 'utf-8').encode()  # 腾讯邮箱略过会导致邮件被屏蔽
    if doc:
        name = os.path.basename(doc)
        f = open(doc, "rb")

        mime = MIMEApplication(f.read())
        # 加上必要的头信息:
        mime.add_header('Content-Disposition', 'attachment', filename=('gbk', '', name))
        # mime.add_header('Content-ID', '<0>')
        # mime.add_header('X-Attachment-Id', '0')
        # # 把附件的内容读进来:
        # mime.set_payload(f.read())
        # # 用Base64编码:
        # encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)

        # 
        # mine = MIMEText(f.read(), 'base64', "gb2312")
        # mine["Content-Type"] = 'application/octet-stream'
        # mine["Content-Disposition"] = 'attachment; filename={}'.format(name)
        # msg.attach(mine)
        f.close()

    # 服务端配置，账密登陆
    server = smtplib.SMTP(smtp_server, 25)
    

    # 腾讯邮箱支持SSL(不强制)， 不支持TLS。
    # server = smtplib.SMTP_SSL(smtp_server, 465) # 按需开启
    # 调试模式，打印日志
    # server.set_debuglevel(1) # 按需开启

    # 登陆服务器
    server.login(from_addr, password)

    # 发送邮件及退出
    server.sendmail(from_addr, [to_addr], msg.as_string())  # 发送地址需与登陆的邮箱一致
    server.quit()


if __name__ == '__main__':
    title = "短视频舆情监控"
    content = "您好:\n  短视频预警监控在附件里"
    doc = 'media/短视频舆情监控-吴钱勇-2020-01-13.xlsx'
    # to_addr = ["wuqianyong@zhongan.com","wuqianyong1995@163.com"]
    to_addr ="wanghaoting@zhongan.com"
    send_email( title, content,to_addr,doc=doc)
